package com.lanyam.travel.base.entity.base;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.lanyam.travel.base.entity.Permission;
import com.lanyam.travel.base.entity.Role;
import com.lanyam.travel.base.entity.User;
import com.lanyam.travel.base.service.UserService;

public class PhoneLoginRealm extends AuthorizingRealm {
	
	@Autowired
    private UserService userService;
	
    /**
     * 用户认证(登录时调用),所有的接口都会走这里获取shiro session中的认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        // 加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        // 获取用户信息
        PhoneToken phoneToken=(PhoneToken)authenticationToken;
        String phone = (String)phoneToken.getPrincipal();
        String password = phoneToken.getCredentials()+"";
        // 通过用户名到数据库查询用户信息
        User user = userService.queryPhoneIsExist(phone);

        if (user == null) {
        	//手机号验证码登陆，第一次登陆时如果不存在用户，则创建
        	user = new User();
        	String id = UUID.randomUUID().toString().replace("-", "");
        	user.setId(id);
        	user.setPhone(phone);
        	user.setStatus(1);
        	user.setCreateDate(new Date());
        	userService.saveUser(user);
        } 

        //账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        
        // 这里验证authenticationToken和simpleAuthenticationInfo的信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(phone,
        		password, getName());
        return simpleAuthenticationInfo;
        
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取登录用户名
        String phone = (String) principalCollection.getPrimaryPrincipal();
        // 查询用户名称
        // 通过用户名到数据库查询用户信息
        User user = userService.queryPhoneIsExist(phone);
        // 添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Role role = userService.getRoleByUserId(user.getId());
        // 添加角色
        simpleAuthorizationInfo.addRole(role.getRole());
        
        List<Permission> permissions = userService.getPermissionsByUserId(user.getId());
        for (Permission permission : permissions) {
            // 添加权限
            simpleAuthorizationInfo.addStringPermission(permission.getName());
        }
        return simpleAuthorizationInfo;
    }
}
